import * as fs from 'fs';
import * as path from 'path';
import { LoggerUtility } from '../logger/logger.utility';
import { Utility } from '../utility/utility';
// tslint:disable-next-line:no-var-requires
const urlencode = require('urlencode');

export class File {
    public upload(ctx, directoryPath): Array<{ name: string, hash: string }> {
        try {
            const files = ctx.request.files.file; // 获取上传文件
            const keys: Array<{ name: string, hash: string }> = [];
            if (Array.isArray(files)) {
                for (const file of files) {
                    let result = this.fileRenameViaUUID(file, directoryPath);
                    result ? keys.push(result) : result = undefined;
                }
            } else {
                let result = this.fileRenameViaUUID(files, directoryPath);
                result ? keys.push(result) : result = undefined;
            }
            return keys;
        } catch (error) {
            LoggerUtility.error('file upload error:', error);
            return [];
        }
    }

    public async download(ctx, directoryPath) {
        try {
            const filename = ctx.request.query.file;
            const filePath = directoryPath + filename;
            const stats = fs.statSync(filePath);
            ctx.set('Content-Type', 'application/octet-stream');
            ctx.set('Content-Disposition', 'attachment; filename=' + urlencode(filename));
            ctx.set('Content-Length', stats.size);
            return ctx.body = fs.createReadStream(filePath);
        } catch (error) {
            LoggerUtility.error('file download error:', error);
        }
    }

    private fileRenameViaUUID(file, directoryPath): { name: string, hash: string } {
        try {
            const ukey = Utility.UUID.next();
            // 创建可读流
            // const reader = fs.createReadStream(file.path);
            // 获取上传文件扩展名
            // let filePath = Config.UPLOAD_PATH + `${file.name}`;
            // 创建可写流
            // const upStream = fs.createWriteStream(filePath);
            // 可读流通过管道写入可写流
            // reader.pipe(upStream);
            const extname = path.extname(file.name);
            fs.rename(file.path, directoryPath + ukey + extname, (err) => {
                if (err) {
                    throw Error('rename error:' + err);
                }
            });
            return { name: file.name, hash: ukey + extname };
        } catch (error) {
            LoggerUtility.error('File.fileRenameViaUUID filename:' + file.name, error);
            return undefined;
        }
    }
}
